import { Button, Drawer, Form, Image, Input, List, message, Modal, Upload, UploadFile } from 'antd';
import React, { useEffect, useState } from 'react';
import { Category } from '@/types/business';
import style from './index.less'
import { request } from '@umijs/max';

interface Props {
  visible: boolean;
  setVisible: (visible: boolean) => void;
  id: number | undefined;
}

function getCategoryOne(id: string | number) {
  return request(`/admin/goods/getCategoryOne?id=${id}`, {
    method: 'post'
  })
}

const SubEditDrawer: React.FC<Props> = ({visible, setVisible, id}) => {

  const [messageApi, contextHolder] = message.useMessage();
  const [form] = Form.useForm()
  const [category, setCategory] = React.useState<Category>({})
  const [edit, setEdit] = React.useState<boolean>(false)
  const [editType, setEditType] = React.useState<string>('add')
  const [editId, setEditId] = React.useState<number | undefined>(undefined)
  const [initialValues, setInitialValues] = React.useState<Category>({})
  const [fileList, setFileList] = React.useState<UploadFile[]>([])
  const [previewImage, setPreviewImage] = useState('')
  const [previewOpen, setPreviewOpen] = useState(false)

  /**
   * 初始化分类信息
   * @param id 一级分类ID
   */
  function initCategoryInfo(id: number) {
    getCategoryOne(id).then(res => {
      setCategory(res.data);
    });
  }

  /**
   * 编辑
   * @param item 要编辑的分类
   */
  const openEdit = (item: Category) => {
    setEdit(true)
    setEditId(item.id)
    setEditType('edit')
    setInitialValues(item)
    setFileList([{
      uid: new Date().getTime().toString(),
      name: '封面图',
      url: item.coverPicUrl,
    }])
  }

  /**
   * 新增
   */
  const openNew = () => {
    setEdit(true)
    setEditType('add')
    setInitialValues({})
    setFileList([])
  }

  const handleClose = () => {
    setEdit(false)
    form.resetFields()
  }

  const handleOk = () => {
    console.log('ok');
    form.validateFields().then((res) => {
      console.log(res, 'validate result');
      form.submit()
    })

  }

  const handlePreview = async (file: UploadFile) => {
    if(file.url) setPreviewImage(file.url)
    setPreviewOpen(true)
  }

  const handleChange = ({file}: {file: UploadFile}) => {
    if(file.status === 'done') {
      console.log(file, 'done');
      setFileList([file])
      form.setFieldValue('coverPicKey', file.response.data.id)
      console.log('set', form.getFieldsValue(true));
    } else {
      console.log(file, 'done');
      setFileList([file])
    }
  }

  const handleSubmit = (values: any) => {
    console.log('submit', values);
    if(editType === 'edit') {
      Object.assign(values, {
        id: editId
      })
    } else {
      // 新增状态
      Object.assign(values, {
        parentId: id,
        level: 2
      })
    }

    request('/admin/goods/saveOrUpdateCategory', {
      method: 'post',
      data: values
    }).then(res => {
      if(res.data === true) {
        messageApi.success('操作成功')
        setEdit(false)
        initCategoryInfo(id!)
      }
    })
  }

  useEffect(() => {
    if(!id || !visible) return
    initCategoryInfo(id);
  }, [visible])

  return (
    <>
      {contextHolder}
      <Drawer title={'二级目录分类'} open={visible} onClose={() => setVisible(false)}>
        <div className={style['category-title']}>
          <div>分类名称：{ category.categoryName }</div>
          <div><Button type={'primary'} onClick={() => openNew()}>新增</Button></div>
        </div>
        <List
          style={{
            marginTop: '20px'
          }}
          itemLayout={'horizontal'}
          dataSource={category.children}
          renderItem={(item) => (
            <List.Item
              key={item.id}
              actions={[
                <a key="list-edit" onClick={() => openEdit(item)}>编辑</a>
              ]}
            >
              <List.Item.Meta
                avatar={<Image width={60} src={item.coverPicUrl}/>}
                title={item.categoryName}
              />
            </List.Item>
          )}
        >
        </List>
        <Modal
          open={edit}
          destroyOnClose={true}
          title={(editType === 'add' ? '新增' : '编辑') + '二级分类'}
          onCancel={() => handleClose()}
          onOk={() => handleOk()}
        >
          <Form
            form={form}
            layout={'vertical'}
            initialValues={initialValues}
            clearOnDestroy={true}
            onFinish={handleSubmit}
          >
            <Form.Item label={'分类名'} name={'categoryName'} rules={[{
              required: true,
              message: '请输入分类名'
            }]}>
              <Input />
            </Form.Item>
            <Form.Item label={'封面图'} name={'coverPicKey'} rules={[{
              required: true,
              message: '请上传封面图',
              validator: (rule, value) => {
                if(!value) {
                  return Promise.reject('请上传封面图')
                }
                return Promise.resolve()
              }
            }]}>
              <div className={style.coverPic}>
                <Upload
                  name="file"
                  action='/api/tools-file/upload'
                  listType={'picture-card'}
                  fileList={fileList}
                  onPreview={handlePreview}
                  data={{
                    modelCode: 'MA001',
                    busiKey: '23466'
                  }}
                  onChange={handleChange}
                >
                  {fileList.length < 1 ? '+ 上传' : '替换'}
                </Upload>
                {previewImage && (
                  <Image
                    wrapperStyle={{ display: 'none' }}
                    preview={{
                      visible: previewOpen,
                      onVisibleChange: (visible) => setPreviewOpen(visible),
                      afterOpenChange: (visible) => !visible && setPreviewImage(''),
                    }}
                    src={previewImage}
                  />
                )}
              </div>
            </Form.Item>
          </Form>
        </Modal>
      </Drawer>
    </>
  )
}

export default SubEditDrawer
